<!-- 点位信息列表信息 -->
<template>
  <div class="q-pa-md bg-white warning-set-container">
    <div style="width: 100%; height: 60px;">
      <q-btn class="q-mr-sm q-mt-xs borderRadius float-right" unelevated padding="8px 8px 7px" icon="add_circle_outline" color="primary" @click="handleCreate" label="添加" />
    </div>
    <q-markup-table flat class="relative-position">
      <thead>
        <th v-for="column in columns" :key="column.name" :class="column.align">
          {{ column.label }}
          <q-icon v-if="column.isSort" class="cursor-pointer" size="18px" :name="descending?'expand_less':'expand_more'" @click="handlerSort" />
        </th>
        <th class="text-center">操作</th>
      </thead>
      <tbody>
        <div v-if="loading">
          <q-inner-loading showing color="grey" />
        </div>
        <tr v-for="row in dataList" :key="row.id">
          <td v-for="column in columns" :key="column.name" :class="column.align">
            {{ row[column.name] }}
          </td>
          <td class="text-center">
            <q-btn
              size="md"
              unelevated
              class="q-mr-xs"
              padding="0 10px"
              :class="themeColor.primary === '#00CBED'?'meijia-ebit-detail-style':'ebit-detail-style'"
              @click="handleUpdate(row)"
              dense
            >
              编辑
            </q-btn>
            <q-btn
              size="md"
              unelevated
              padding="0 10px"
              :outline="themeColor.primary === '#00CBED'"
              :class="themeColor.primary === '#00CBED'?'meijia-delete-style':'delete-style'"
              @click="handleDelete(row)"
              dense
            >
              删除
            </q-btn>
          </td>
        </tr>
      </tbody>
    </q-markup-table>
  </div>
    <!-- 添加/编辑 弹出对话框 -->
  <q-dialog v-model="isAddOrUpdate" persistent>
    <q-card class="card-style">
        <!-- 对话框的头部 -->
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">{{ tempTitLe[dialogTitle] }}</div>
        <q-space />
        <q-btn icon="close" flat round dense @click="closeEbitUpdate"></q-btn>
      </q-card-section>
        <!-- 对话框的主体-->
      <q-card-section>
        <q-form ref="assetForm" class="q-pa-sm dialog-form-container">
          <ul>
            <li>
              <span>阈值名称</span>
              <span>
                <q-select
                  dense
                  options-dense
                  outlined
                  v-model="creatUpdateQuery.threshold_name"
                  :options="deviceNameOptions"
                  @update:model-value="changeThresholdName"
                />
              </span>
            </li>
            <li>
              <span>
                阀值上限
              </span>
              <span>
                <q-input
                  outlined
                  dense
                  v-model="creatUpdateQuery.up_value"
                />
              </span>
            </li>
            <li>
              <span>
                阈值下限
              </span>
              <span>
                <q-input
                  outlined
                  dense
                  v-model="creatUpdateQuery.down_value"
                />
              </span>
            </li>
            <li>
              <span>
                阈值上限是否使能
              </span>
              <span>
                <q-checkbox
                  dense
                  v-model="creatUpdateQuery.up_enable"
                  label="使能通知"
                />
              </span>
            </li>
            <li>
              <span>
                阈值下限是否使能
              </span>
              <span>
                <q-checkbox
                  dense
                  v-model="creatUpdateQuery.down_enable"
                  label="使能通知"
                />
              </span>
            </li>
            <li>
              <span>告警等级</span>
              <span>
                <q-select
                  dense
                  options-dense
                  outlined
                  v-model="creatUpdateQuery.alert_level_one"
                  :options="alertLevelA"
                />
              </span>
            </li>
             <li>
              <span>
                单位
              </span>
              <span>
                <q-input
                  disable
                  outlined
                  dense
                  v-model="creatUpdateQuery.uom"
                />
              </span>
            </li>
          </ul>
        </q-form>
      </q-card-section>
        <!-- 对话框的底部 -->
      <q-card-actions align="right">
        <q-btn unelevated label="取消" type="reset" style="color: #686868;" outline @click="closeEbitUpdate" />
        <q-btn unelevated label="确定" type="submit" color="accent" @click="dialogTitle==='create'?handlerCreateSensor():handlerUpdateSensor()" />
      </q-card-actions>
    </q-card>
  </q-dialog>
  <!-- 删除 提示框 -->
  <DeleteDialog :isShowDelete="isShowDelete" :tipInfo="'确定删除该条告警设置吗？'" @closeDeleteDialog="closeDeleteDialog" @confirmDelete="confirmDelete" />
</template>

<script>
import { ref } from 'vue'
import { fetchSiteList,  setSiteInfo, fetchSiteNameList, addSiteInfo, deleteSiteInfo  } from 'src/api/systemtWarning'
import { mapGetters } from 'vuex';
import DeleteDialog from 'src/components/deleteDialog/index'
export default {
  props: {
    setSiteId: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      dataList: [],

      columns: [
        { name: 'idIndex', label: 'ID', align: 'text-center',field: 'idIndex', isSort: true},
        { name: 'threshold_name', label: '告警名称', align: 'text-center',field: 'threshold_name'},
        { name: 'up_value', align: 'text-center', label: '上限值', field: 'up_value'},
        { name: 'down_value', align: 'text-center', label: '下限值', field: 'down_value' },
        { name: 'uom', align: 'text-center', label: '单位', field: 'uom' },
        { name: 'up_enable', align: 'text-center', label: '上限使能', field: 'up_enable' },
        { name: 'down_enable', align: 'text-center', label: '下限使能', field: 'down_enable' },
        { name: 'alert_level_string', align: 'text-center', label: '告警等级', field: 'alert_level_string' },
      ],

      // 表格头部
      headerSeach: ref(),
       // 右侧表头选择
      visibleColumns: ref([]),
      queryList: {
        ordering: 'id'
      },
      loading: false,
      isAddOrUpdate: false, // 添加/编辑
      creatUpdateQuery: {
        threshold_name: '',
        up_value: '',
        up_enable: false,
        down_value: '',
        down_enable: false,
        alert_level_one: '',
        uom: ''
      },
      alertLevelA: [
        { value: '低', label: '低', alert_level: 1 },
        { value: '中', label: '中', alert_level: 2 },
        { value: '高', label: '高', alert_level: 3 },
      ],
      deviceNameOptions: [],
      dialogTitle: 'create',
      tempTitLe: {
        'create': '添加监测点位告警信息',
        'update': '修改监测点位告警信息'
      },
      isShowDelete: false,
      descending: false
    }
  },

  components: { DeleteDialog },
  computed: {
    ...mapGetters(['themeColor'])
  },
  watch: {
    setSiteId: {
      immediate: true,
      handler(val) {
        if (!val || val === 0) return
        this.feathOranizerList()
        this.getAlertNameList()
      }
    }
  },
  beforeCreate() {
  },
  mounted() {
  },

  methods: {
    // 刷新
    handlerRefresh() {
      this.feathOranizerList()
    },
    /**
     * 获取资产信息的列表
     */
    feathOranizerList() {
      this.loading = true
      this.queryList.ordering = 'id'
      this.queryList.point_id = this.setSiteId
      fetchSiteList(this.queryList).then(res => {
        const { status, data } = res
        if (status === 200) {
          this.dataList = data
          this.dataList.forEach((item, index) => {
            if (this.queryList.ordering === 'id') {
              item.idIndex = index + 1
            } else {
              item.idIndex = this.dataList.length - index
            }
          })
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
      })
    },
    /**
     * 关闭 添加/编辑 弹出对话框
     */
    closeEbitUpdate() {
      this.isAddOrUpdate = false
    },
    /**
     * 获取告警名称列表
     */
    getAlertNameList() {
      this.deviceNameOptions = []
      fetchSiteNameList({ point_id: this.setSiteId }).then(res => {
        const { status, data } = res
        if (status === 200) {
          if (data && data.length > 0) {
            data.forEach(element => {
              let { value_type, threshold_name, uom } = element
              this.deviceNameOptions.push({
                value: threshold_name,
                label: threshold_name,
                threshold_name,
                value_type,
                uom
              })
            })
          }
        }
      })
    },
    /**
     * 重置添加参数
     */
    resetQuery() {
      this.creatUpdateQuery = {
        threshold_name: '',
        up_value: '',
        up_enable: false,
        down_value: '',
        down_enable: false,
        alert_level_one: null,
        uom: ''
      }
    },
    /**
     * 切换阈值名称
     */
    changeThresholdName(val) {
      if (!val) return
      if (val && val.value_type) {
        this.creatUpdateQuery.uom = val.uom
      }
    },
    /**
     * 添加
     */
    handleCreate() {
      this.resetQuery()
      this.isAddOrUpdate = true
      this.dialogTitle = 'create'
    },
    handlerCreateSensor() {
      let _query = Object.assign({}, this.creatUpdateQuery)
      _query.value_type = _query.threshold_name.value_type
      _query.point_id = this.setSiteId
      _query.alert_level = _query.alert_level_one.alert_level
      delete _query.alert_level_one
      delete _query.threshold_name
      addSiteInfo(_query).then(res => {
        const { status, data } = res
        this.isAddOrUpdate = false
        if (status === 200) {
          this.feathOranizerList()
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: '添加成功！'
          })
        }
      })
    },
    /**
     * 编辑
     */
    handleUpdate(val) {
      if (!val) return
      this.dialogTitle = 'update'
      this.isAddOrUpdate = true
      this.creatUpdateQuery = Object.assign({}, val)
      if (this.creatUpdateQuery.threshold_name) {
        this.creatUpdateQuery.threshold_name = this.deviceNameOptions.find(item => item.value === val.threshold_name)
      }
      if (this.creatUpdateQuery.alert_level_string) {
        this.creatUpdateQuery.alert_level_one = this.alertLevelA.find(item => item.value === val.alert_level_string)
      }
      this.$nextTick(res => {
        this.$refs.assetForm.resetValidation()
      })
    },
    handlerUpdateSensor() {
      this.$refs.assetForm.validate().then(success => {
        if (success) {
          const editEquip = Object.assign({}, this.creatUpdateQuery)
          editEquip.value_type = editEquip.threshold_name.value_type
          editEquip.alert_level = editEquip.alert_level_one.alert_level
          delete editEquip.alert_level_one
          delete editEquip.threshold_name
          setSiteInfo(this.creatUpdateQuery.id, editEquip).then(res => {
            this.isAddOrUpdate = false
            if (res.status === 200) {
              this.feathOranizerList()
              this.$q.notify({
                type: 'positive',
                position: 'top',
                message: '编辑成功！'
              })
            }
          })
        }
      })
    },
    /**
     * 删除
     */
    handleDelete(val) {
      this.isShowDelete = true
      if (val) this.deleteId = val.id
    },
    /**
     * 删除成功
     */
    confirmDelete() {
      if (!this.deleteId) return
      deleteSiteInfo(this.deleteId).then(res => {
        const { status } =  res
        if (status === 200) {
          this.isShowDelete = false
          this.feathOranizerList()
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: '已删除！'
          })
        }
      })
    },
    /**
     * 关闭删除提示框
     */
    closeDeleteDialog() {
      this.isShowDelete = false
    },
    /**
     * 排序
     */
    handlerSort() {
      this.descending = !this.descending
      this.dataList.reverse()
    }
  }
}

</script>
<style lang='scss' scoped>
// 固定操作列
.my-sticky-column-table {
  tr:first-child {
    th:last-child {
      background: #fff;
    }
  }
  td {
    &:last-child {
      background: #fff;
    }
  }
  th:last-child, td:last-child {
    position: sticky;
    right: 0;
    z-index: 1;
  }
}
// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      height: 42px;
      line-height: 42px;
      white-space: nowrap;
      margin-bottom: 30px;
      >span {
        &:first-child {
          display: inline-block;
          width: 150px;
          margin-right: 5px;
        }
        &:last-child {
          display: inline-block;
          width: 200px;
          >.q-input {
            width: 200px;
          }
        }
      }
    }
  }
}

.click-row {
  background-color: rgba(0,0,0,0.06) !important;
}
.warning-set-container {
  height: 400px;
  overflow: auto;
}
</style>
